﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using GroundWater.Data;
using GroundWater.BusinessActions;

using UserTable = GroundWater.Data.UserDataSet.UsersDataTable;
using UserRow = GroundWater.Data.UserDataSet.UsersRow;

using MonitoringTable = GroundWater.Data.MonitoringDataSet.MonitoringDataTable;
using MonitoringRow = GroundWater.Data.MonitoringDataSet.MonitoringRow;
using System.Data;


namespace GroundWater.Admin
{
    public partial class usermanager : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SiteUtil.Validate(this, "用户管理");

        }

        protected void RowDataBound(object sender, GridViewRowEventArgs args)
        {
            GridView gridView = (GridView)sender;

            if (gridView.SortExpression.Length > 0)
            {
                int cellIndex = -1;
                foreach (DataControlField field in gridView.Columns)
                {
                    if (field.SortExpression == gridView.SortExpression)
                    {
                        cellIndex = gridView.Columns.IndexOf(field);
                        break;
                    }
                }

                if (cellIndex > -1)
                {
                    if (args.Row.RowType == DataControlRowType.Header)
                    {
                        //  this is a header row,
                        //  set the sort style
                        args.Row.Cells[cellIndex].CssClass +=
                            (gridView.SortDirection == SortDirection.Ascending
                            ? " sortasc" : " sortdesc");
                    }
                }
            }

            if (args.Row.RowType == DataControlRowType.DataRow)
            {
                if (args.Row.RowIndex > -1)
                {
                    if (args.Row.Cells[5].Controls.Count > 0)
                    {
                        LinkButton btnDelete = args.Row.Cells[5].Controls[0] as LinkButton;
                        if (btnDelete != null && btnDelete.Text == "删除")
                        {
                            btnDelete.OnClientClick = "return confirm('您是否确认删除此项？');";
                        }
                    }
                }
            }
        }

        protected void odsUsers_Deleting(object sender, ObjectDataSourceMethodEventArgs e)
        {
            e.InputParameters["id"] = e.InputParameters["UserName"];
            e.InputParameters.Remove("UserName");

            int cnt = Users.DeleteAuthByUserId(e.InputParameters["id"].ToString());

            if (cnt > 0)
            {
                //e.Cancel = true;
                //sm.RegisterDataItem(updPanel, "1");//updPanel
            }
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            GridViewRow row = ((LinkButton)sender).Parent.Parent as GridViewRow;
            string userId = this.gvUsers.DataKeys[row.RowIndex].Value.ToString();
            SetFields(userId);

            updPnl.Update();
            txtUsername.Enabled = false;

            mdlPopup.Show();
        }

        private void SetFields(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                UserRow row = Users.GetById(id, false);
                if (!row.IsUserRoleNull())
                {
                    txtUserRole.Text = row.UserRole;
                }

                if (!row.IsDescriptionNull())
                {
                    txtDescription.Text = row.Description;
                }
                txtUsername.Text = row.UserName;
                txtPassword.Text = row.Password;

                this.ViewState["UserId"] = id;
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            if (txtUsername.Text.Trim().Length == 0 || txtPassword.Text.Length == 0) return;
            string userId = this.ViewState["UserId"] as String;

            UserDataSet user = GetFields(userId);
            if (user == null)
            {
                lblJavaScript.Text = "<script type=\"text/javascript\">alert('已存在用户：" + txtUsername.Text.Trim() + " ');</script>";
            }

            Users.Update(user, false, true, new string[] { user.Users.TableName });

            gvUsers.DataBind();

            updPanel.Update();
            this.ViewState.Remove("UserId");

            ClearFields();
        }

        private void ClearFields()
        {
            //throw new NotImplementedException();
            txtDescription.Text = "";
            txtPassword.Text = "";
            txtUsername.Text = "";
            txtUserRole.Text = "";
        }

        private UserDataSet GetFields(string id)
        {
            UserRow user = null;

            if (String.IsNullOrEmpty(id))
            {
                UserRow row = GroundWater.BusinessActions.Users.GetById(txtUsername.Text.Trim(), false);
                if (row != null)
                {
                    return null;
                }

                user = (new UserDataSet()).Users.NewUsersRow();
                //user.Code = "";
                //user.Name = "";
                user.Description = "";
                user.UserRole = "dd";
                
            }
            else
            {
                // update
                user = Users.GetById(id, false);
            }
            user.UserName = txtUsername.Text;
            user.Password = txtPassword.Text;
            user.UserRole = txtUserRole.Text;


            user.Description = txtDescription.Text;

            if (String.IsNullOrEmpty(id))
            {
                user.Table.Rows.Add(user);
            }
            else
            {

            }

            return user.Table.DataSet as UserDataSet;
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            txtUsername.Enabled = true;
            mdlPopup.Show();
        }

        //
        protected void btnEditAuth_Click(object sender, EventArgs e)
        {
            GridViewRow row = ((LinkButton)sender).Parent.Parent as GridViewRow;
            string userId = this.gvUsers.DataKeys[row.RowIndex].Value.ToString();
            //SetFields(userId);
            this.ViewState["UserId"] = userId;

            udpAuthorization.Update();
            //txtUsername.Enabled = false;
            lblUsername.Text = userId;//SiteUtil.GetString("Username");
            DataTable dt = Users.FetchAuthByUserId(userId);
            string s = Husb.Util.CommonUtil.DataColumn2String(dt, 1, false);
            txtMenus.Value = s;

            mpeAuth.Show();
        }
        protected void btnSaveAuth_Click(object sender, EventArgs e)
        {
            //if (txtUsername.Text.Trim().Length == 0 || txtPassword.Text.Length == 0) return;
            string userId = this.ViewState["UserId"] as String;


            foreach (ListItem item in cblMenus.Items)
            {
                if (item.Selected)
                {
                    string s = item.Text;
                    DataTable dt = Users.FetchAuthByUserId(userId, item.Value);
                    if (dt == null || dt.Rows.Count == 0)
                    {
                        Users.InsertAuth(userId, item.Value);
                    }
                }
                else
                {
                    Users.DeleteAuth(userId, item.Value);
                }
            }

            var menus = txtMenus.Value;
            //UserDataSet user = GetFields(userId);

            //Users.Update(user, false, true, new string[] { user.Users.TableName });

            //gvUsers.DataBind();

            //updPanel.Update();
            this.ViewState.Remove("UserId");

            //ClearFields();
        }

        protected void cblMenus_DataBound(object sender, EventArgs e)
        {
            foreach (ListItem i in cblMenus.Items)
            {
                i.Attributes["name"] = i.Value;
            }
            
        }
    }
}
